﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml;

namespace iPhoneUI.Shell
{
    public class Select : Config
    {
        public Select(XmlNode config)
            : base(config)
        {
        }

        public object Evaluate(XmlNode context, Type type)
        {
            XmlNode operation = GetNode().FirstChild;
            if (operation != null)
            {
                if (operation.Name == "count")
                    return SelectCount(context, operation.InnerText);

                if (operation.Name == "text")
                    return SelectText(context, operation.InnerText, type);

                if (operation.Name == "position-of")
                    return SelectPositionOf(context, operation.Attributes["node-select"], operation.Attributes["list-select"]);
            }

            return string.Empty;
        }

        private static int SelectCount(XmlNode context, string xpath)
        {
            return context.SelectNodes(xpath).Count;
        }

        private static object SelectText(XmlNode context, string xpath, Type type)
        {
            XmlNode node = context.SelectSingleNode(xpath);
            if (node != null)
                return node.CoerceInnerText(type);

            return string.Empty;
        }

        private static int SelectPositionOf(XmlNode context, XmlAttribute nodeSelect, XmlAttribute listSelect)
        {
            if (nodeSelect == null || listSelect == null)
                return -1;

            return context.SelectSingleNode(nodeSelect.InnerText).Position(context.SelectNodes(listSelect.InnerText));
        }
    }
}
